import { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react'
import { Modal, Select } from 'antd'
import './chooseField.css'
import ChooseField from '@/views/ShoppingCart/components/ChooseField.tsx'
import {
  getOrderItemDetail,
  getOrderItemMappings,
  getPgAllFieldsByIdAndTableName,
  getPgAllTablesById,
  updateOrderItemMapTable
} from '@/api/shoppingCart.ts'
import { initPageType, usePageChange } from '@hs-admin/utils'

const initPage: initPageType = {
  pageSize: 20,
  current: 1,
  morePageOptions: {},
  total: 0
}

const ChooseFieldModal = forwardRef(({ updateList }: { updateList: () => void }, ref) => {
  const [open, setOpen] = useState(false)

  const [orderItemInfo, setOrderItemInfo] = useState({
    id: '',
    productId: '',
    tableName: '',
    mappingTableName: '',
    dbId: ''
  })

  const [options, setOptions] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const [fieldList, setFieldList] = useState<
    Array<{
      name: string
      comment: string
      description: string
    }>
  >([])

  const [tableOptions, setTableOptions] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const [keyWords, setKeyWords] = useState('')

  const showModal = ({
    productId,
    id,
    tableName,
    mappingTableName,
    dbId
  }: {
    productId: string
    id: string
    tableName: string
    mappingTableName: string
    dbId: string
  }) => {
    setOrderItemInfo({
      id,
      productId,
      tableName,
      mappingTableName,
      dbId
    })

    setOpen(true)
  }

  const handleCancel = () => {
    updateList()
    setOpen(false)
  }

  useEffect(() => {
    if (orderItemInfo.dbId && orderItemInfo.mappingTableName) {
      setOptions([])
      getPgAllFieldsByIdAndTableName(orderItemInfo.dbId, {
        table_name: orderItemInfo.mappingTableName,
        page: 1,
        page_size: 9999
      }).then((res) => {
        console.log(res, 'F')
        setOptions(
          (res ?? []).map((it) => ({
            label: (
              <div className="flex gap-2">
                {it[0]}
                <span className="text-sm text-gray">{it[1] && `(${it[1]})`}</span>
              </div>
            ),
            value: it[0]
          }))
        )
      })
    }
  }, [orderItemInfo.dbId, orderItemInfo.mappingTableName])

  useEffect(() => {
    if (orderItemInfo.productId) {
      setFieldList([])
      getOrderItemMappings(orderItemInfo.productId).then((res) => {
        setFieldList(res.items)
      })
    }
  }, [orderItemInfo.productId])

  const doRequest = useCallback(
    async (page: number, pageSize: number) => {
      if (!orderItemInfo.dbId) throw 'no db id'
      setTableOptions([])
      const res = await getPgAllTablesById(orderItemInfo.dbId, {
        page,
        page_size: pageSize,
        keywords: keyWords
      })
      setTableOptions(
        res.items.map((it) => ({
          label: it.name,
          value: it.name
        }))
      )
      return 0
    },
    [keyWords, orderItemInfo.dbId]
  )
  const { purePagination, handleChange, resetPageAndTriggerRequest } = usePageChange(initPage, doRequest)

  const getMoreOption = () => {
    if (purePagination.current * purePagination.pageSize < purePagination.total) {
      handleChange(purePagination.current + 1)
    }
  }
  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  useImperativeHandle(ref, () => ({
    showModal
  }))

  return (
    <Modal width="80vw" open={open} title="选择所需字段" onCancel={handleCancel} footer={null}>
      <div>
        <h3>配置同步映射关系</h3>
        <div className="flex items-center gap-2">
          <span>{orderItemInfo.tableName}</span> <span className="font-bold text-2xl">{'->'}</span>
          <Select
            className="flex-1"
            showSearch
            value={orderItemInfo.mappingTableName}
            onSearch={(value) => {
              setKeyWords(value || '')
            }}
            options={tableOptions}
            onPopupScroll={getMoreOption}
            onChange={async (value) => {
              await updateOrderItemMapTable(orderItemInfo.id, { mapping_table_name: value })
              const res = await getOrderItemDetail(orderItemInfo.id)
              setOrderItemInfo({
                ...orderItemInfo,
                mappingTableName: res.mapping_table_name
              })
            }}
          />
        </div>
        <ChooseField fieldList={fieldList} options={options} orderId={orderItemInfo.id} mappingTableName={orderItemInfo.mappingTableName} />
      </div>
    </Modal>
  )
})

export default ChooseFieldModal
